package com.by.service.impl;

import com.by.constant.AuthConstants;
import com.by.factory.LoginStrategyFactory;
import com.by.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ServivE
 * @version 0.1
 * @className UserDetailsServiceImpl
 * @description
 * @date 2024/12/4 19:49
 * @since jdk17
 */

/**
 * UserDetailsService是Spring Security提供的接口之一，
 * 它是一个中央服务，负责从数据源（如数据库、文件、LDAP等）中加载用户的详细信息，并进行身份验证
 * 任何实现UserDetailsService接口的对象都可以作为认证数据源，也就是说UserDetailsService接口用来加载用户信息，
 * 之后再封装成Spring Security能够识别的数据UserDetails对象，供Spring Security进行身份验证和授权操作。
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private LoginStrategyFactory loginStrategyFactory;
    /**
     * Spring Security框架核心业务的拓展
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 从请求头中获取请求的登录类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        // 判断登录类型是否有值
        if (!StringUtils.hasText(loginType)) {
            // 登录类型不存在，抛出异常
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
        // 使用策略模式，实现不同情况的处理方案
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        if (ObjectUtils.isEmpty(instance)) {
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
        return instance.realLogin(username);
    }
}
